package com.flowplan.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 异步配置
 * 利用Java 21虚拟线程优化Excel处理和AI服务调用性能
 * 目标：10MB Excel文件处理时间<30秒
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    /**
     * Excel处理异步执行器
     * 使用Java 21虚拟线程处理Excel解析
     */
    @Bean("excelProcessorExecutor")
    public Executor excelProcessorExecutor() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }

    /**
     * AI服务异步执行器
     * 使用虚拟线程优化AI服务调用
     */
    @Bean("aiServiceExecutor")
    public Executor aiServiceExecutor() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }

    /**
     * 通用异步执行器
     * 用于其他异步任务
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("FlowPlan-Task-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    /**
     * WebSocket消息处理执行器
     * 使用虚拟线程优化实时协作性能
     */
    @Bean("websocketExecutor")
    public Executor websocketExecutor() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }
}